#include "ui.hpp"
#include "input.hpp"
#include "menu.hpp"
bool g_quit = false;
bool ui_quit = false;
string shell_path = "";

#define MAN_AUTO_SKIP
void cmdThread(string name,int * ret){
	int result = 0;
	result = system(name.c_str());
	if(WEXITSTATUS(result) == MANWAI){
		return;
	}
	*ret = WEXITSTATUS(result);
#ifdef MAN_AUTO_SKIP
	ui_quit = true;
#endif
	return;
	
};

struct ManBind {
	ManMenu * menu;
	ManShellUI * ui;
};

int keyboard_ui(int in,void *data,bool * quit){
	int cur_page = 0;
	ManBind * bind = (ManBind *)data;
	ManShellUI * ui = bind->ui;
	ManMenu * menu = bind->menu;
	cur_page = ui->getPage();
	switch(in){
		case MAN_LEFT:
			cur_page--;
			ui->setPage(cur_page);
			break;
		case MAN_RIGHT:
			cur_page++;
			ui->setPage(cur_page);
			break;
		case MAN_QUIT:
			ui_quit = true;
			*quit = true;
			break;
		case MAN_PAS:
			menu->setState(MANPAS);
			ui_quit = true;
			*quit = true;
			break;
		case MAN_ERR:
			menu->setState(MANERR);
			ui_quit = true;
			*quit = true;
			break;
		default:
			break;
	}


	return 0;
}

int keyboard_menu(int in,void *data,bool * quit){
	int cur_sel = 0;
	string name;
	string name_stop;
	ManBind bind;
	ManMenu * menu = (ManMenu *)data;
	cur_sel = menu->getSel();
	switch(in){
		case MAN_UP:
			cur_sel--;
			menu->setSel(cur_sel);
			break;
		case MAN_DOWN:
			cur_sel++;
			menu->setSel(cur_sel);
			break;
		case MAN_QUIT:
			g_quit = true;
			*quit = true;
			break;
		case MAN_ENTER:
			{
				int ret = MANNON;
				name = menu->getName();
				name_stop = shell_path + "/" + name + " stop";
				string fifo = "/tmp/";
				fifo += name;
				ManShellUI ui(name);
				
				name = shell_path + "/" + name + " > /tmp/" + name;
				
				ui.setPageMax(50);
				ui.start(fifo);
				thread cmd;
				cmd = thread(cmdThread,name,&ret);
				bind.menu = menu;
				bind.ui = &ui;

				ManInput input(keyboard_ui,&bind);
				while(!ui_quit){
					usleep(1000);
				}
				
				if(ret != MANNON){
					menu->setState(ret);
				}
				
				if (cmd.joinable()){
					system(name_stop.c_str());
					pthread_cancel(cmd.native_handle());
					cmd.join();
				}

				ui_quit = false;
			}
		
			break;
		default:
			break;
	}

	menu->update();
	return 0;
}

int main(int argc, char ** argv){
	string usage = "USAGE: ";
	usage += argv[0];
	usage += " <path>";
	if(argc != 2 && argv[1] == NULL){
		cout << usage << endl;
		return -1;
	}
	shell_path = argv[1];
	ManMenu menu(shell_path);
	ManInput input(keyboard_menu,&menu);
/*
	ManShellUI ui("TEST");
	ui.setPageMax(50);
	ManInput input(keyboard_ui,&ui);
	ui.start("test");
*/
	while(!g_quit){
		usleep(1000 * 1000);
	}
	return 0;
}
